package com.gitee.cirnochat.common.utils;


import com.gitee.cirnochat.common.exception.BusinessException;
import com.gitee.cirnochat.common.model.enums.ErrorCode;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.UUID;

public final class FileUploadValidationUtil {

    private FileUploadValidationUtil() {
        // Prevent instantiation
        throw new UnsupportedOperationException("Utility class");
    }

    public static void validateFileNotEmpty(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
    }

    public static void validateFileType(MultipartFile file, String expectedType) {
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith(expectedType)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误，必须为" + expectedType);
        }
    }

    public static void validateFileSize(MultipartFile file, long maxSize) {
        if (file.getSize() > maxSize) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小超过限制，最大为" + (maxSize / (1024 * 1024)) + "MB");
        }
    }

    public static void validateTotalFileSize(MultipartFile[] files, long maxTotalSize) {
        long totalSize = Arrays.stream(files).mapToLong(MultipartFile::getSize).sum();
        if (totalSize > maxTotalSize) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件总大小超过限制，最大为" + (maxTotalSize / (1024 * 1024)) + "MB");
        }
    }

    public static void validateFileCount(MultipartFile[] files, int maxCount) {
        if (files.length > maxCount) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件数量超过限制，最大为" + maxCount + "个");
        }
    }

    public static String getRandomUploadFileName() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);
    }

    public static void validateFileNotEmpty(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
    }

    public static void validateFileType(String contentType, String expectedType) {
        if (contentType == null || !contentType.startsWith(expectedType)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误，必须为" + expectedType);
        }
    }

    public static void validateFileSize(byte[] bytes, int maxSize) {
        if (bytes.length > maxSize) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小超过限制，最大为" + (maxSize / (1024 * 1024)) + "MB");
        }
    }
}